package com.link.base.base.approval.service;

import com.link.base.base.approval.dao.mybatis.mapper.ApprovalRuleMapper;
import com.link.base.base.approval.model.ApprovalRule;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.interceptor.SecurityInterceptor;
import com.link.core.basic.query.Filter;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.util.QueryParamUtil;
import org.eclipse.jetty.util.StringUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 审批规则-审批规则 
 *
 * @author 姚江漪
 * @date 2019/05/29 14:12
 */
@Service
public class ApprovalRuleServiceImpl extends BasicServiceImpl<ApprovalRule> implements ApprovalRuleService {

    @Resource
    private ApprovalRuleMapper approvalRuleMapper;

    @Resource
    private RestTemplate restTemplate;
    
    @Override
    public BasicMapper<ApprovalRule> getBasicMapper() {
        return approvalRuleMapper;
    }

    /**
     * 查询未关联该流程的规则
     *
     * @author 姚江漪
     * @date 2019/05/29 14:12
     */
    @Override
    public List<ApprovalRule> queryUnSelectFlowListPage(ApprovalRule record) throws Exception {
        return approvalRuleMapper.queryUnSelectFlowListPage(record);
    }

    /**
     * 校验是否存在符合规则的审批流程
     *
     * @author 姚江漪
     * @date 2019/05/29 14:12
     */
    @Override
    public String checkRules(String flowType,String recordId) throws Exception {
        String flowId = "";
        if (StringUtil.isBlank(flowType)) {
            throw new BasicServiceException("type 不能为空！");
        }
        ApprovalRule approvalRuleQuery = (ApprovalRule) QueryParamUtil.addQpsFilter(ApprovalRule.class,
                new Filter("flowType", flowType),
                new Filter("status", "Y"),
                new Filter("flowStatus", "Active"));
        approvalRuleQuery.setPageFlag(false);
        List<ApprovalRule> approvalRuleList = this.queryByExamplePage(approvalRuleQuery);

        int count = 0;
        for (int i = 0;i < approvalRuleList.size();i++) {
            ApprovalRule approvalRule = approvalRuleList.get(i);
            String rules = "";
            if (StringUtil.isBlank(approvalRule.getRule())) {
                rules = "[{\"id\":\"id\",\"property\":\"id\",\"value\":\"" + recordId + "\"}]";
            } else {
                rules = "[" + approvalRule.getRule() + ",{\"id\":\"id\",\"property\":\"id\",\"value\":\"" + recordId + "\"}]";
            }
            // 接口调用路径
            String postUrl = "http://" + approvalRule.getModuleName() + approvalRule.getUrl();
            HttpHeaders headers = new HttpHeaders();
            String token = SecurityInterceptor.token.get();
            headers.add("Authorization", "bearer " + token);
            Map<String , Object> map = new HashMap<>();
            map.put("filtersRaw", rules);
            HttpEntity entity = new HttpEntity<Object>(map, headers);
            Map resultMap = restTemplate.postForObject(postUrl, entity, Map.class);
            Boolean successFlg = (Boolean) resultMap.get("success");
            if (!successFlg) {
                throw new BasicServiceException(resultMap.get("result").toString());
            }
            List resultList = (List)resultMap.get("rows");
            if (resultList.size() > 0) {
                flowId = approvalRule.getFlowId();
                count++;
            }
        }
        if (count == 0) {
            throw new BasicServiceException("查找不到审批流程，请联系系统管理员！");
        } else if (count > 1) {
            throw new BasicServiceException("查找到多个审批流程，请联系系统管理员！");
        }
        return flowId;
    }
}

